package com.dolphin.common.db;

import com.dolphin.common.annotation.TargetDataSource;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Created by hhwf on 2017/10/15.
 */
@Aspect
@Component
@Order(value = -1)
public class DynamicDataSourceAspect{


    @Before("@annotation(com.dolphin.common.annotation.TargetDataSource)")
    public void before(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod(); //获取被拦截的方法
        Method realMethod = null;
        try {
            realMethod = joinPoint.getTarget().getClass().getDeclaredMethod(signature.getName(), method.getParameterTypes());
        } catch (NoSuchMethodException e) {
            DynamicDataSourceHolder.setDataSource("dataSourceWrite");
            return;
        }
        if (realMethod.isAnnotationPresent(TargetDataSource.class)) {
            String targetDataSource = realMethod.getAnnotation(TargetDataSource.class).dataSource();
            DynamicDataSourceHolder.setDataSource(targetDataSource);
        }else {
            DynamicDataSourceHolder.setDataSource("dataSourceWrite");
        }
    }


    @After("@annotation(com.dolphin.common.annotation.TargetDataSource)")
    public void afterReturning(JoinPoint joinPoint) {
        DynamicDataSourceHolder.clearDataSource();
    }



}

